<template>
  <view class="inbound-container">
    <z-paging ref="paging" v-model="orderList" @query="getList">
      <!-- 搜索栏 -->
    <view slot="top" class="search-bar">
      <!-- 将搜索框替换为下拉选择框 -->
      <uni-data-select
        v-model="queryParams.projectId"
        :localdata="project_list"
        placeholder="请选择项目"
        @change="handleProjectChange"
        class="project-select"
      />
    </view>
    <!-- 订单列表 -->
    <view class="order-list">
      <uni-card 
        v-for="(order, index) in orderList" 
        :key="index" 
        :margin="margin"
        @click="viewOrderDetail(order)"
        class="clickable-card"
      >
        <view class="order-header">
          <text class="order-title">入库订单：{{getProjectName(order.projectId)}}</text>
          <uni-tag :text="getTagType(order.orderStatus)" :type="getStatusColorType(order.orderStatus)" size="small" />
        </view>
      
      
        <view class="order-info">
          <view class="info-item">
            <text class="label">出行方式：</text>
            <text class="value">{{gettransport(order.transportType)}}</text>
          </view>
          <view class="info-item">
            <text class="label">司机:</text>
            <text class="value">{{getDriverName(order.driver) }}</text>
          </view>
          <!-- 移除详情按钮和footer部分 -->
        </view>
       
      </uni-card>
    </view>

    <!-- 悬浮添加按钮 -->
    <view class="fab-button" @click="navigateToCreate">
      <image src="/static/images/icon/add.png" mode="aspectFit" class="fab-icon" />
    </view>
   </z-paging>
  </view>
</template>

<script>
import { listOrder} from "@/api/mes/order"
import { getProjectAll } from "@/api/mes/project"
import { listCar } from "@/api/mes/car"
import { getDicts } from "@/api/system/dict/data" // 引入字典API
import { listDriver } from "@/api/mes/projectExtend"

export default {
  data() {
    return {
      margin: ['10rpx', '10rpx'],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        orderType: 1,
        orderStatus: null,
      },
      orderList: [
        // 可以添加更多订单数据
      ],
      car_list: [],
      project_list: [
      ],
      // 字典数据
      transport_type: [],
      order_status: []
    }
  },
  onLoad() {
    this.getList();
    this.getProjectList();
    this.getCarList();
    this.getDictData(); // 获取字典数据
    this.getDriverList();
  },
  methods: {
    // 添加项目选择变更处理方法
    handleProjectChange(e) {
      this.search();
    },
    getDriverList() {
      listDriver().then(response => {
        this.driver_list = response.data.map(driver => ({
          value: driver.userId.toString(),
          text: driver.nickName
        }));
      }); 
    },
    getDriverName(driver) {
      if (!driver) return '-';
      const driverItem = this.driver_list.find(item => item.value === driver.toString());
      return driverItem? driverItem.text : driver;
    },
    // 修改搜索方法
    search() {
      // Reset to first page when searching
      this.$refs.paging.reload();
      
      if (this.loading) return Promise.reject()
      this.loading = true
      
      uni.showLoading({
        title: '加载中...'
      })
      listOrder(this.queryParams).then(response => {
        this.$refs.paging.completeByTotal(response.rows, response.total);
        this.loading = false
        uni.hideLoading()
      }).catch(error => {
        console.error('搜索项目失败', error)
        this.loading = false
        uni.hideLoading()
        uni.showToast({
          title: '搜索项目失败',
          icon: 'none'
        })
      })
    },
    
    // 添加重置搜索方法
    resetSearch() {
      this.queryParams.projectId = null;
      this.search();
    },
    // 获取字典数据
    getDictData() {
      getDicts('transport_type').then(response => {
        this.transport_type = response.data;
      });
      getDicts('order_status').then(response => {
        this.order_status = response.data
      });
    },
    // 根据字典类型和值获取字典标签
    getDictLabel(dict, value) {
      const data = this[dict];
      const result = data.find(item => item.dictValue === value);
      return result ? result.dictLabel : '';
    },
    getTagType(statusId) {
      // 状态类型映射
      if (!statusId) return 'default';
      // 先查找字典中的状态
      const statusItem = this.order_status.find(item => item.dictValue === statusId.toString());
      
      // 如果找到了状态项，返回对应的标签文本
      if (statusItem) {
        // 这里返回状态的文本标签
        return statusItem.dictLabel || 'default';
      }
      // 如果没找到，直接返回默认类型
      return 'default';
    },
    
    // 新增一个方法用于获取标签颜色类型
    getStatusColorType(statusId) {
      // 状态类型映射
      const typeMap = {
        '0': 'primary',   // 蓝色
        '1': 'primary',   // 绿色
        '2': 'primary',   // 黄色
        '3': 'primary',     // 红色
        '4': 'primary',      // 灰色
        '5': 'primary',    // 紫色
        '6': 'primary',     // 皇家蓝
        '7': 'primary',     // 橙色
        '8': 'success' 
      };
      
      if (!statusId) return 'default';
      
      return typeMap[statusId] || 'default';
    },
    navigateToCreate() {
      uni.navigateTo({
        url: '/packageOrder/pages/inbound-create'
      })
    },
    viewOrderDetail(order) {
      uni.navigateTo({
        url: `/packageOrder/pages/inbound-detail?id=${order.orderId}&orderType=${order.orderType}`
      })
    },
    getList(pageNo, pageSize) {
      this.queryParams.pageNum = pageNo;
      this.queryParams.pageSize = pageSize;
      if (this.loading) return Promise.reject()
      this.loading = true
      
      uni.showLoading({
        title: '加载中...'
      })
    listOrder(this.queryParams).then(response => {
        this.$refs.paging.completeByTotal(response.rows, response.total);
        this.loading = false
        uni.hideLoading()
    }).catch((error) => {
        console.error('查询订单列表', error)
        this.loading = false
        uni.hideLoading()
        uni.showToast({
          title: '查询订单列表',
          icon: 'none'
        })
      });
   },
   getCarList() {
    listCar().then(response => {
      this.car_list = response.data.map(car => ({
            value: car.carId.toString(),
            text: car.carNo
          }));
    });
 },
  getProjectList() {
      getProjectAll().then(response => {
        this.project_list = response.rows.map(project => ({
              value: project.projectId,
              text:  project.projectName,
            }));
      });
    },
    // 根据车辆ID获取车辆名称
    gettransport(carId) {
      if (!carId) return '-';
      const car = this.transport_type.find(item => item.dictValue === carId.toString());
      return car ? car.dictLabel : carId;
    },
    getProjectName(projectId) {   
      if (!projectId) return '-';
      const project = this.project_list.find(item => item.value === projectId);
      return project ? project.text : projectId;
    },
  }
}
</script>

<style lang="scss" scoped>
.inbound-container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f5f5;

  .order-list {
    padding-bottom: 120rpx;
  }
  
  .clickable-card {
    transition: all 0.2s ease;
    
    &:active {
      transform: scale(0.98);
      opacity: 0.9;
    }
  }
  
  .search-bar {
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    
    .project-select {
      flex: 1;
      margin-right: 20rpx;
    }
    
    .search-btn, .reset-btn {
      margin-left: 10rpx;
      height: 70rpx;
      line-height: 70rpx;
    }
  }
  position: relative;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .order-title {
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .order-info {
    .info-item {
      display: flex;
      margin-bottom: 16rpx;

      .label {
        color: #666;
        width: 160rpx;
      }

      .value {
        flex: 1;
      }
    }
  }

  .order-footer {
    margin-top: 20rpx;
    display: flex;
    justify-content: flex-end;

    .detail-btn {
      margin-left: 20rpx;
    }
  }

  .fab-button {
    position: fixed;
    right: 30rpx;
    bottom: 30rpx;
    width: 100rpx;
    height: 100rpx;
    background-color: #007AFF;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.15);
    z-index: 99;

    .fab-icon {
      width: 50rpx;
      height: 50rpx;
    }
    .is-hover {
      color: rgba(69, 20, 204, 0.6);
      background-color: #2d10b0;
      border-color: #2d10b0;
      }
  }
}
</style>